package com.fengplus.demo.service.impl;

import com.fengplus.demo.entity.AppOrder;
import com.fengplus.demo.entity.AppProduct;
import com.fengplus.demo.entity.AppUser;
import com.fengplus.demo.mapper.AppOrderMapper;
import com.fengplus.demo.service.OrderService;
import com.fengplus.demo.service.ProductService;
import com.fengplus.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AppOrderMapper orderMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Override
    public List<AppOrder> findList() {
        return orderMapper.findList();
    }

    @Override
    public AppOrder findOne(Long id) {
        return orderMapper.findOne(id);
    }

    @Override
    @Transactional
    public int save(AppOrder order) {
        AppUser user = userService.findOne(order.getUserId());
        AppProduct product = productService.findOne(order.getProductId());
        order.setAmount(product.getPrice().multiply(new BigDecimal(order.getCount())));
        order.setBody(product.getTitle() + "X" + order.getCount());
        order.setSn("LS" + System.currentTimeMillis() );
        int orderResult = orderMapper.save(order);
//        if(orderResult > 0){
//            throw new RuntimeException("临时错误");
//        }
        productService.decreaseStock(product.getId(), order.getCount());
        return 1;
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        return orderMapper.updateStatus(id, status);
    }

    @Override
    public int delete(Long id) {
        return orderMapper.delete(id);
    }

}
